import logging
import time

import pyautogui


def print_mouse_position_on_move():
    last_x, last_y = pyautogui.position()  # 初始化上一次的鼠标位置

    try:
        while True:
            current_x, current_y = pyautogui.position()
            if current_x != last_x or current_y != last_y:
                print(f"当前鼠标位置: ({current_x}, {current_y})")
                last_x, last_y = current_x, current_y  # 更新上一次的鼠标位置
            time.sleep(0.1)  # 减少检查间隔以提高响应速度
    except KeyboardInterrupt:
        print("程序已停止")


def calculate_relative_positions(coordinates, origin_name):
    """
    计算所有坐标的相对位置
    :param coordinates: 包含名字和坐标的字典
    :param origin_name: 原点的名称
    :return: 相对位置字典
    """
    origin_x, origin_y = coordinates[origin_name]
    relative_positions = {}
    for name, (x, y) in coordinates.items():
        relative_x = x - origin_x
        relative_y = y - origin_y
        relative_positions[name] = (relative_x, relative_y)
    return relative_positions


def move_mouse_to_coordinate(relative_positions, origin_name, target_name, origin_coordinates, adjust_x=0, adjust_y=0):
    """
    将鼠标移动到指定名称的相对位置
    :param relative_positions: 相对位置字典
    :param origin_name: 原点的名称
    :param target_name: 目标坐标的名称
    :param origin_coordinates: 原点的实际坐标
    :param adjust_x 调整x
    :param adjust_y 调整y
    """
    origin_x, origin_y = origin_coordinates[origin_name]
    relative_x, relative_y = relative_positions[target_name]

    # 移动鼠标到目标位置
    target_x = origin_x + relative_x + adjust_x
    target_y = origin_y + relative_y + adjust_y
    pyautogui.moveTo(target_x, target_y)
    logging.info(f"鼠标移动到 {target_name} 的位置: ({target_x}, {target_y})")
    return target_x, target_y


def update_origin_coordinates(relative_positions, new_origin_coordinates):
    """
    更新原点坐标并重新计算实际坐标
    :param relative_positions: 相对位置字典
    :param new_origin_coordinates: 新的原点实际坐标
    :return: 新的实际坐标字典
    """
    new_origin_x, new_origin_y = new_origin_coordinates
    new_coordinates = {}
    for name, (relative_x, relative_y) in relative_positions.items():
        new_x = new_origin_x + relative_x
        new_y = new_origin_y + relative_y
        new_coordinates[name] = (new_x, new_y)
    return new_coordinates


def move_to_new_origin(coordinates, origin_name, new_origin_coordinates, target_name, adjust_x=0, adjust_y=0):
    relative_positions = calculate_relative_positions(coordinates, origin_name)
    new_coordinates = update_origin_coordinates(relative_positions, new_origin_coordinates)
    return move_mouse_to_coordinate(relative_positions, origin_name, target_name, new_coordinates, adjust_x=adjust_x, adjust_y=adjust_y)


def enable_x_y(x, y):
    if x == 0 or y == 0:
        return False
    return True


def move_and_click(target_x, target_y):
    pyautogui.moveTo(target_x, target_y)
    logging.info(f"鼠标移动到的位置: ({target_x}, {target_y})")
    time.sleep(1)
    pyautogui.click(target_x, target_y)
    return target_x, target_y
